#!/usr/bin/python3
# -*- coding: utf-8 -*-

from configparser import ConfigParser
from json import dumps, loads
from os import path
from sys import exit

from requests import request

from modules.api.base_translation import BaseTranslation
from modules.utils import MY_ERROR_CODES, check_langs, get_file_encoding, print_err, print_warn

# 所有支持的语种字典
_CAIYUN_COMMON_LANGS = ['zh', 'en', 'ja']

# 源语种字典
_CAIYUN_FROM_LANGS = {
    '1': {'n': '汉语', 'c': 'zh'},
    '2': {'n': '英语', 'c': 'en'},
    '3': {'n': '日语', 'c': 'ja'},
}

# 常用目标语种字典
_CAIYUN_TO_LANGS = {
    '1': {'n': '汉语', 'c': 'zh'},
    '2': {'n': '英语', 'c': 'en'},
    '3': {'n': '日语', 'c': 'ja'},
}


class CaiyunTranslation(BaseTranslation):
    '''
    彩云小译API
    '''

    def __init__(self, section: str):

        BaseTranslation.__init__(self, section)
        self.section = section

        self._token = ''
        if self._conf and len(self._conf) > 0:
            self._token = self._conf['token']
        if self._token == '':
            print_err('翻译API启用失败，请在api_keys.ini中配置token！')
            exit(0)

        self._get_config()

    def translate(self, source_txt: str, to_lang: str, from_lang='en') -> str:
        '''
        开始翻译

        - source_txt: 输入文本
        - to_lang: 目标语种
        - from_lang: 源语种
        '''

        # 由于彩云源语言无法使用auto，故在此检测语言语种
        from_lang = check_langs(source_txt).lower()

        # 当源语言不在受支持的语种范围内时，强制将源语言设置为en，确保翻译能正常进行
        if not from_lang in _CAIYUN_COMMON_LANGS:
            from_lang = 'en'
            print_warn('检测的源语言不在受支持的语种范围内，已强制重置为“英语”！')

        # 当源语言不在受支持的语种范围内时，强制将源语言设置为zh，确保翻译能正常进行
        if not to_lang in _CAIYUN_COMMON_LANGS:
            to_lang = 'zh'
            print_warn('目标语言不在受支持的语种范围内，已强制重置为“汉语”！')

        if to_lang == from_lang:
            print_warn('目标语种和源语种相同。')
            return source_txt

        # 原文本长度超过上限
        if len(source_txt) > self._max_char:
            print_err(MY_ERROR_CODES['ERR_10002'])
            return 'ERR_10002'

        url = "http://api.interpreter.caiyunai.com/v1/translator"
        token = self._token

        payload = {
            "source": [source_txt],
            "trans_type": from_lang + "2" + to_lang,
            "request_id": "demo",
        }

        headers = {
            'content-type': "application/json",
            'x-authorization': "token " + token,
        }

        try:
            response = request("POST", url, data=dumps(payload), headers=headers)
            # TODO 后续增加处理翻译API无法使用时的逻辑
            # if response['status_code'] == 402:
            #     return
            target = loads(response.text)['target'][0]
        except Exception as e:
            print_err(f'翻译出现异常：{e.args[0]}！')
            target = 'ERR_10001'
        return target

    def _get_config(self):
        '''
        获取配置
        '''

        config_path = path.join(
            path.abspath('.'), 'modules', 'api', 'caiyun', 'config.ini'
        )
        if not path.isfile(config_path):
            return

        conf = ConfigParser()  # 调用读取配置模块中的类
        conf.optionxform = lambda option: option
        conf.read(config_path, encoding=get_file_encoding(config_path))

        self._rate = conf.getint(self.section, 'rate')
        if self._rate < 1:
            self._rate = 1
        self._max_char = conf.getint(self.section, 'max_char')
        if self._max_char < 50:
            self._max_char = 2000

    def get_from_langs(self) -> dict:
        '''
        统一函数。获取源语种字典
        '''
        return _CAIYUN_FROM_LANGS

    def get_to_langs(self) -> dict:
        '''
        统一函数。获取目标语种字典
        '''
        return _CAIYUN_TO_LANGS
